<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';
require_once 'includes/functions.php';

$db = Database::getInstance();

// 初始化变量
$gameId = isset($_GET['game_id']) ? (int)$_GET['game_id'] : 0;
$resourceId = isset($_GET['resource_id']) ? (int)$_GET['resource_id'] : 0;
$game = null;
$resource = null;
$configContent = '';
$message = '';
$messageType = '';

// 检查游戏是否存在
if ($gameId > 0) {
    $game = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "games WHERE id = ?", [$gameId]);
    
    if (!$game) {
        $_SESSION['flash_message'] = '游戏不存在';
        $_SESSION['flash_type'] = 'danger';
        header('Location: games.php');
        exit;
    }
}

// 获取配置文件资源
if ($resourceId > 0) {
    $resource = $db->fetchRow(
        "SELECT * FROM " . DB_PREFIX . "game_resources WHERE id = ? AND game_id = ? AND type = 'config'", 
        [$resourceId, $gameId]
    );
    
    if (!$resource) {
        $_SESSION['flash_message'] = '配置文件不存在或不属于此游戏';
        $_SESSION['flash_type'] = 'danger';
        header('Location: game_resources.php?game_id=' . $gameId);
        exit;
    }
    
    // 读取配置文件内容
    $filePath = '../' . $resource['file_path'];
    if (file_exists($filePath)) {
        $configContent = file_get_contents($filePath);
        
        // 尝试格式化JSON以便于编辑
        $fileExt = strtolower(pathinfo($resource['filename'], PATHINFO_EXTENSION));
        if ($fileExt == 'json') {
            $decodedContent = json_decode($configContent);
            if ($decodedContent !== null) {
                $configContent = json_encode($decodedContent, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            }
        }
    } else {
        $message = '配置文件不存在于服务器上';
        $messageType = 'danger';
    }
}

// 处理配置文件保存
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_config'])) {
    $newContent = isset($_POST['config_content']) ? $_POST['config_content'] : '';
    
    // 验证JSON格式（如果是JSON文件）
    $fileExt = strtolower(pathinfo($resource['filename'], PATHINFO_EXTENSION));
    $isValid = true;
    
    if ($fileExt == 'json') {
        $decodedContent = json_decode($newContent);
        if ($decodedContent === null && json_last_error() !== JSON_ERROR_NONE) {
            $isValid = false;
            $message = 'JSON格式无效: ' . json_last_error_msg();
            $messageType = 'danger';
        }
    }
    
    if ($isValid) {
        // 保存更新后的内容
        $filePath = '../' . $resource['file_path'];
        $result = file_put_contents($filePath, $newContent);
        
        if ($result !== false) {
            $message = '配置文件已成功保存';
            $messageType = 'success';
            
            // 更新资源记录的修改时间
            $db->update('game_resources', [
                'updated_at' => date('Y-m-d H:i:s')
            ], 'id = ?', [$resourceId]);
            
            // 更新当前显示的内容
            $configContent = $newContent;
        } else {
            $message = '保存配置文件失败，请检查文件权限';
            $messageType = 'danger';
        }
    }
}

// 创建新配置文件
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_config'])) {
    $configName = isset($_POST['config_name']) ? trim($_POST['config_name']) : '';
    $configType = isset($_POST['config_type']) ? trim($_POST['config_type']) : 'json';
    $initialContent = isset($_POST['initial_content']) ? $_POST['initial_content'] : '';
    
    if (empty($configName)) {
        $message = '请输入配置文件名称';
        $messageType = 'danger';
    } else {
        // 确保文件名有正确的扩展名
        if (!preg_match('/\.' . $configType . '$/i', $configName)) {
            $configName .= '.' . $configType;
        }
        
        // 创建目录结构
        $resourcesDir = '../uploads/games/' . $gameId . '/config/';
        if (!is_dir($resourcesDir)) {
            mkdir($resourcesDir, 0755, true);
        }
        
        // 生成唯一文件名
        $newFileName = 'config_' . uniqid() . '.' . $configType;
        $filePath = $resourcesDir . $newFileName;
        $relativePath = 'uploads/games/' . $gameId . '/config/' . $newFileName;
        
        // 写入初始内容
        if ($configType == 'json' && !empty($initialContent)) {
            // 验证JSON格式
            $decodedContent = json_decode($initialContent);
            if ($decodedContent === null && json_last_error() !== JSON_ERROR_NONE) {
                $message = 'JSON格式无效: ' . json_last_error_msg();
                $messageType = 'danger';
            } else {
                // 格式化JSON
                $initialContent = json_encode($decodedContent, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            }
        }
        
        // 如果没有错误，创建文件
        if (empty($message)) {
            $result = file_put_contents($filePath, $initialContent);
            
            if ($result !== false) {
                // 在数据库中记录资源
                $resourceData = [
                    'game_id' => $gameId,
                    'type' => 'config',
                    'filename' => $configName,
                    'file_path' => $relativePath,
                    'created_at' => date('Y-m-d H:i:s')
                ];
                
                $newResourceId = $db->insert('game_resources', $resourceData);
                
                $message = '配置文件已成功创建';
                $messageType = 'success';
                
                // 重定向到编辑新创建的配置文件
                header('Location: game_config_edit.php?game_id=' . $gameId . '&resource_id=' . $newResourceId);
                exit;
            } else {
                $message = '创建配置文件失败，请检查目录权限';
                $messageType = 'danger';
            }
        }
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-code-square"></i> 游戏配置编辑器</h1>
    <div>
        <a href="game_resources.php?game_id=<?php echo $gameId; ?>" class="btn btn-primary">
            <i class="bi bi-archive"></i> 资源管理
        </a>
        <a href="game_preview.php?id=<?php echo $gameId; ?>" class="btn btn-success">
            <i class="bi bi-eye"></i> 预览游戏
        </a>
        <a href="games.php" class="btn btn-secondary">
            <i class="bi bi-arrow-left"></i> 返回游戏列表
        </a>
    </div>
</div>

<?php if (!empty($message)): ?>
<div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
    <?php echo $message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>

<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-info-circle"></i> 游戏信息
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-3">
                <?php if (!empty($game['image'])): ?>
                    <img src="<?php echo '../' . htmlspecialchars($game['image']); ?>" alt="游戏图片" class="img-fluid rounded">
                <?php else: ?>
                    <div class="text-center p-4 bg-light rounded">
                        <i class="bi bi-image fs-1"></i>
                        <p class="mt-2">暂无游戏图片</p>
                    </div>
                <?php endif; ?>
            </div>
            <div class="col-md-9">
                <h3><?php echo htmlspecialchars($game['name']); ?></h3>
                <p class="text-muted"><?php echo htmlspecialchars($game['category']); ?> | 
                   难度: <?php echo str_repeat('★', $game['difficulty']) . str_repeat('☆', 5 - $game['difficulty']); ?> | 
                   年龄: <?php echo $game['min_age'] . '-' . $game['max_age']; ?>岁
                </p>
                <p><?php echo nl2br(htmlspecialchars($game['description'])); ?></p>
            </div>
        </div>
    </div>
</div>

<?php if (!$resource): ?>
<!-- 创建新配置文件表单 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-plus-circle"></i> 创建新的配置文件
    </div>
    <div class="card-body">
        <form action="" method="post">
            <div class="row mb-3">
                <div class="col-md-6">
                    <label for="config_name" class="form-label">配置文件名称</label>
                    <input type="text" class="form-control" id="config_name" name="config_name" required placeholder="例如: game_settings.json">
                    <div class="form-text">为您的配置文件提供一个描述性的名称</div>
                </div>
                <div class="col-md-6">
                    <label for="config_type" class="form-label">配置文件类型</label>
                    <select class="form-select" id="config_type" name="config_type">
                        <option value="json">JSON - JavaScript Object Notation</option>
                        <option value="xml">XML - eXtensible Markup Language</option>
                        <option value="csv">CSV - Comma Separated Values</option>
                    </select>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="initial_content" class="form-label">初始内容</label>
                <textarea class="form-control code-editor" id="initial_content" name="initial_content" rows="15" placeholder="输入配置内容，对于JSON文件，请确保格式正确">{}</textarea>
                <div class="form-text">为新配置文件提供初始内容。对于JSON文件，系统会自动验证和格式化内容</div>
            </div>
            
            <div class="mb-3">
                <button type="submit" name="create_config" class="btn btn-primary">
                    <i class="bi bi-save"></i> 创建配置文件
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 配置文件模板 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-list"></i> 配置文件模板
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-4 mb-3">
                <div class="card h-100">
                    <div class="card-header">基础游戏设置</div>
                    <div class="card-body">
                        <p class="small">适用于大多数游戏的基本配置，包括难度设置、时间限制等</p>
                        <button type="button" class="btn btn-sm btn-outline-primary use-template" data-template="basic">
                            使用此模板
                        </button>
                    </div>
                </div>
            </div>
            <div class="col-md-4 mb-3">
                <div class="card h-100">
                    <div class="card-header">记忆力游戏配置</div>
                    <div class="card-body">
                        <p class="small">专为记忆类游戏设计的配置，包括卡片数量、匹配规则等</p>
                        <button type="button" class="btn btn-sm btn-outline-primary use-template" data-template="memory">
                            使用此模板
                        </button>
                    </div>
                </div>
            </div>
            <div class="col-md-4 mb-3">
                <div class="card h-100">
                    <div class="card-header">益智问答游戏</div>
                    <div class="card-body">
                        <p class="small">问答游戏配置模板，包括问题列表、答案选项和分数规则</p>
                        <button type="button" class="btn btn-sm btn-outline-primary use-template" data-template="quiz">
                            使用此模板
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php else: ?>
<!-- 编辑现有配置文件 -->
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <div>
            <i class="bi bi-code-square"></i> 
            编辑配置文件: <?php echo htmlspecialchars($resource['filename']); ?>
        </div>
        <div>
            <a href="<?php echo '../' . $resource['file_path']; ?>" class="btn btn-sm btn-outline-secondary" target="_blank">
                <i class="bi bi-eye"></i> 在新窗口查看
            </a>
            <a href="<?php echo '../' . $resource['file_path']; ?>" class="btn btn-sm btn-outline-success" download>
                <i class="bi bi-download"></i> 下载文件
            </a>
        </div>
    </div>
    <div class="card-body">
        <form action="" method="post">
            <div class="mb-3">
                <div class="d-flex justify-content-between mb-2">
                    <label for="config_content" class="form-label">
                        配置内容
                        <?php 
                        $fileExt = strtolower(pathinfo($resource['filename'], PATHINFO_EXTENSION));
                        echo '<span class="badge bg-info">' . strtoupper($fileExt) . ' 文件</span>';
                        ?>
                    </label>
                    <div>
                        <button type="button" id="formatBtn" class="btn btn-sm btn-outline-secondary" <?php echo $fileExt != 'json' ? 'disabled' : ''; ?>>
                            <i class="bi bi-text-indent-left"></i> 格式化JSON
                        </button>
                    </div>
                </div>
                <textarea class="form-control code-editor" id="config_content" name="config_content" rows="25"><?php echo htmlspecialchars($configContent); ?></textarea>
                <div class="form-text">
                    <?php if ($fileExt == 'json'): ?>
                        编辑JSON配置时，请确保保持正确的语法格式，系统会自动验证。
                    <?php else: ?>
                        请确保您了解此文件格式的正确语法。
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="mb-3">
                <button type="submit" name="save_config" class="btn btn-primary">
                    <i class="bi bi-save"></i> 保存配置
                </button>
                <a href="game_resources.php?game_id=<?php echo $gameId; ?>" class="btn btn-secondary">
                    <i class="bi bi-x"></i> 取消
                </a>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- 加载ACE编辑器 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 为textarea创建ACE编辑器实例
    const setupEditor = function(elementId) {
        const textarea = document.getElementById(elementId);
        if (!textarea) return;
        
        // 创建一个div来放置编辑器
        const editorDiv = document.createElement('div');
        editorDiv.id = elementId + '_editor';
        editorDiv.style.height = textarea.offsetHeight + 'px';
        editorDiv.style.width = '100%';
        editorDiv.style.fontSize = '14px';
        
        // 插入编辑器div，隐藏textarea
        textarea.parentNode.insertBefore(editorDiv, textarea);
        textarea.style.display = 'none';
        
        // 创建ACE编辑器
        const editor = ace.edit(editorDiv.id);
        editor.setValue(textarea.value);
        
        // 设置编辑器主题和选项
        editor.setTheme('ace/theme/monokai');
        
        // 根据文件类型设置模式
        <?php if (isset($resource)): ?>
        const fileExtension = '<?php echo $fileExt; ?>';
        <?php else: ?>
        const fileExtension = document.getElementById('config_type')?.value || 'json';
        <?php endif; ?>
        
        if (fileExtension === 'json') {
            editor.session.setMode('ace/mode/json');
        } else if (fileExtension === 'xml') {
            editor.session.setMode('ace/mode/xml');
        } else if (fileExtension === 'csv') {
            editor.session.setMode('ace/mode/text');
        }
        
        // 在编辑器中更改时更新textarea的值
        editor.session.on('change', function() {
            textarea.value = editor.getValue();
        });
        
        return editor;
    };
    
    <?php if ($resource): ?>
    // 设置配置内容编辑器
    const configEditor = setupEditor('config_content');
    
    // 格式化JSON按钮
    const formatBtn = document.getElementById('formatBtn');
    if (formatBtn) {
        formatBtn.addEventListener('click', function() {
            try {
                const content = configEditor.getValue();
                const jsonObj = JSON.parse(content);
                const formatted = JSON.stringify(jsonObj, null, 2);
                configEditor.setValue(formatted);
                configEditor.clearSelection();
            } catch (e) {
                alert('JSON格式错误: ' + e.message);
            }
        });
    }
    <?php else: ?>
    // 设置初始内容编辑器
    const initialEditor = setupEditor('initial_content');
    
    // 配置文件类型变更时更新编辑器模式
    const configTypeSelect = document.getElementById('config_type');
    if (configTypeSelect) {
        configTypeSelect.addEventListener('change', function() {
            const fileType = this.value;
            if (fileType === 'json') {
                initialEditor.session.setMode('ace/mode/json');
            } else if (fileType === 'xml') {
                initialEditor.session.setMode('ace/mode/xml');
            } else if (fileType === 'csv') {
                initialEditor.session.setMode('ace/mode/text');
            }
        });
    }
    
    // 配置模板选择按钮
    const templateButtons = document.querySelectorAll('.use-template');
    templateButtons.forEach(button => {
        button.addEventListener('click', function() {
            const templateType = this.getAttribute('data-template');
            let templateContent = '';
            
            switch (templateType) {
                case 'basic':
                    templateContent = JSON.stringify({
                        "gameSettings": {
                            "difficultyLevels": [
                                {"name": "简单", "timeLimit": 60, "scoreMultiplier": 1.0},
                                {"name": "中等", "timeLimit": 45, "scoreMultiplier": 1.5},
                                {"name": "困难", "timeLimit": 30, "scoreMultiplier": 2.0}
                            ],
                            "defaultDifficulty": "中等",
                            "enableTutorial": true,
                            "enableSound": true,
                            "enableMusic": true
                        },
                        "gameContent": {
                            "title": "游戏标题",
                            "description": "游戏说明文本",
                            "startMessage": "游戏开始提示",
                            "endMessage": "游戏结束提示",
                            "gameOverMessage": "游戏失败提示"
                        },
                        "rewards": {
                            "scoreThresholds": [
                                {"threshold": 100, "reward": "铜牌", "message": "恭喜获得铜牌！"},
                                {"threshold": 300, "reward": "银牌", "message": "恭喜获得银牌！"},
                                {"threshold": 500, "reward": "金牌", "message": "恭喜获得金牌！"}
                            ]
                        }
                    }, null, 2);
                    break;
                case 'memory':
                    templateContent = JSON.stringify({
                        "gameSettings": {
                            "difficultyLevels": [
                                {"name": "简单", "gridSize": [4, 4], "timeLimit": 120, "scoreMultiplier": 1.0},
                                {"name": "中等", "gridSize": [6, 5], "timeLimit": 180, "scoreMultiplier": 1.5},
                                {"name": "困难", "gridSize": [6, 6], "timeLimit": 240, "scoreMultiplier": 2.0}
                            ],
                            "defaultDifficulty": "中等",
                            "cardRevealTime": 1.0,
                            "enableHints": true,
                            "maxHints": 3
                        },
                        "gameContent": {
                            "cardThemes": ["动物", "水果", "交通工具"],
                            "defaultTheme": "动物",
                            "cardBackImage": "card_back.png",
                            "cardSets": {
                                "动物": [
                                    {"id": 1, "name": "狮子", "image": "lion.png"},
                                    {"id": 2, "name": "熊猫", "image": "panda.png"},
                                    {"id": 3, "name": "大象", "image": "elephant.png"}
                                    // 添加更多卡片...
                                ]
                            }
                        },
                        "scoring": {
                            "correctMatch": 10,
                            "incorrectMatch": -2,
                            "timeBonus": true,
                            "timeBonusFormula": "剩余时间 * 0.5"
                        }
                    }, null, 2);
                    break;
                case 'quiz':
                    templateContent = JSON.stringify({
                        "gameSettings": {
                            "difficultyLevels": [
                                {"name": "简单", "timePerQuestion": 30, "scoreMultiplier": 1.0},
                                {"name": "中等", "timePerQuestion": 20, "scoreMultiplier": 1.5},
                                {"name": "困难", "timePerQuestion": 10, "scoreMultiplier": 2.0}
                            ],
                            "defaultDifficulty": "中等",
                            "randomizeQuestions": true,
                            "randomizeAnswers": true,
                            "questionsPerRound": 10
                        },
                        "questions": [
                            {
                                "id": 1,
                                "question": "问题文本",
                                "options": ["选项A", "选项B", "选项C", "选项D"],
                                "correctAnswer": 0,
                                "category": "常识",
                                "difficulty": "简单",
                                "explanation": "答案解释"
                            },
                            {
                                "id": 2,
                                "question": "另一个问题文本",
                                "options": ["选项A", "选项B", "选项C", "选项D"],
                                "correctAnswer": 1,
                                "category": "科学",
                                "difficulty": "中等",
                                "explanation": "答案解释"
                            }
                            // 添加更多问题...
                        ],
                        "scoring": {
                            "correctAnswer": 10,
                            "incorrectAnswer": 0,
                            "timeBonus": true,
                            "timeBonusFormula": "剩余时间 * 0.2"
                        },
                        "categories": ["常识", "科学", "历史", "地理", "文学"]
                    }, null, 2);
                    break;
            }
            
            if (templateContent) {
                initialEditor.setValue(templateContent);
                initialEditor.clearSelection();
                
                // 如果是JSON模板，自动设置文件类型为JSON
                if (configTypeSelect) {
                    configTypeSelect.value = 'json';
                }
                
                // 根据模板类型生成推荐的文件名
                const configNameInput = document.getElementById('config_name');
                if (configNameInput) {
                    switch (templateType) {
                        case 'basic':
                            configNameInput.value = 'game_settings.json';
                            break;
                        case 'memory':
                            configNameInput.value = 'memory_game_config.json';
                            break;
                        case 'quiz':
                            configNameInput.value = 'quiz_questions.json';
                            break;
                    }
                }
            }
        });
    });
    <?php endif; ?>
});
</script>

<?php
require_once 'includes/footer.php';
?> 